<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
      <el-breadcrumb-item>活动详情</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区 -->
    <el-card>
      <div>
        <!-- 搜索区 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input placeholder="请输入内容"
                      class="input-with-select"
                      v-model="queryInfo.query"
                      clearable
                      @clear="getUserList">
              <el-button slot="append"
                         icon="el-icon-search"
                         @click="getUserList"></el-button>
            </el-input>
          </el-col>
          <el-col :span="8">
            <el-button type="primary"
                       round
                       @click="addUser">添加用户</el-button>
          </el-col>
        </el-row>
      </div>
      <!-- 列表区 -->
      <div>
        <el-table :data="users"
                  style="width: 100%">
          <el-table-column prop="id"
                           label="#">
          </el-table-column>
          <el-table-column prop="username"
                           label="姓名">
          </el-table-column>
          <el-table-column prop="mobile"
                           label="手机">
          </el-table-column>
          <el-table-column prop="role_name"
                           label="角色">
          </el-table-column>
          <el-table-column prop="email"
                           label="邮箱">
          </el-table-column>
          <!-- true或false无法渲染在页面当中 -->
          <el-table-column prop="mg_state"
                           label="状态">
            <template slot-scope="scope">
              <!-- {{scope.row}} -->
              <el-switch v-model="scope.row.mg_state"
                         @change="changeStatus(scope.row)">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary"
                         icon="el-icon-edit"
                         @click="showEditUser(scope.row.id)"
                         size="mini"></el-button>
              <el-button type="danger"
                         icon="el-icon-delete"
                         @click="deleteEditUser(scope.row.id)"
                         size="mini"></el-button>
              <el-tooltip class="item"
                          effect="dark"
                          content="分配角色"
                          placement="top">
                <el-button type="warning "
                           @click="setRole(scope.row.id)"
                           icon="el-icon-setting"
                           size="mini"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页区 -->
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="currentPage"
                     :page-sizes="[1, 2, 3, 4]"
                     :page-size="pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="totalRecords">
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框组件 -->
    <el-dialog title="添加用户"
               :visible.sync="dialogFormVisible"
               @close="addDialogClosed">
      <el-form :model="addForm"
               ref="addFormRef"
               :rules="addFormRules"
               label-width="70px">
        <el-form-item label="用户名"
                      prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码"
                      prop="password">
          <el-input v-model="addForm.password"
                    type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱"
                      prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机"
                      prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary"
                   @click="submitUser()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改用户对话框组件 -->
    <el-dialog title="修改用户"
               :visible.sync="editDialogFormVisible"
               @close="editDialogClosed">
      <el-form :model="editForm"
               ref="editFormRef"
               :rules="addFormRules"
               label-width="70px">
        <el-form-item label="用户名"
                      prop="username"
                      disabled>
          <el-input v-model="editForm.username"
                    disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱"
                      prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机"
                      prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary"
                   @click="submitEditUser()">修 改</el-button>
      </div>
    </el-dialog>

    <!-- 分配角色提示框 -->
    <el-dialog title="分配角色"
               :visible.sync="setRoleDialogVisible"
               @close="closeSetRole"
               width="30%">
      <div>当前用户：{{tempUser.username}}</div>
      <div>当前角色：{{tempUser.role_name}}</div>
      <div>当前角色Id：{{tempUser.roleId}}</div>
      <el-select v-model="selectRoleId"
                 placeholder="请选择" @change="selectRole">
        <el-option v-for="item in roleList"
                   :key="item.id"
                   :label="item.roleName"
                   :value="item.id">
        </el-option>
      </el-select>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="submitSetRole(tempUser.id,selectRoleId)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    var email = (rule, value, callback) => {
      const reg = /^([a-zA-Z]|[0-9])(\w|\w)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
      if (reg.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法邮箱'))
    }

    var phone = (rule, value, callback) => {
      const reg = /^[1][3,4,5,7,8,9][0-9]{9}$/
      if (reg.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法手机号'))
    }

    return {
      queryInfo: {
        query: '',
        pagesize: 1,
        pagenum: 1
      },
      users: [],
      totalRecords: 0,
      currentPage: 1,
      pageSize: 1,
      // 控制对话框的显示与隐藏
      dialogFormVisible: false,
      // 控制编辑对话框的显示与隐藏
      editDialogFormVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        phone: ''
      },
      editForm: {
        phone: ''
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名3-10位', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名3-10位', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          //   { min: 3, max: 10, message: '合法邮箱', trigger: 'blur' },
          { validator: email, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: phone, trigger: 'blur' }
        ]
      },
      // 控制分配角色提示框的显示或隐藏
      setRoleDialogVisible: false,
      // 临时选中的对象记录
      tempUser: {},
      // 角色数组对象
      roleList: [],
      selectRoleId: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      this.users = res.data.users
      this.totalRecords = res.data.total
    },
    handleSizeChange (val) {
      this.queryInfo.pagesize = val
      this.getUserList()
    },
    handleCurrentChange (val) {
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    async changeStatus (userInfo) {
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.msg_state}`
      )
      if (res.meta.status !== 200) {
        userInfo.msg_state = !userInfo.msg_state
        this.$message.error('更新失败')
      }
      this.$message.success('更新成功')
    },
    // 添加新用户按钮事件
    addUser () {
      this.dialogFormVisible = true
    },
    cancel () {
      this.dialogFormVisible = false
      this.editDialogFormVisible = false
    },
    // 监听对话框关闭后重置表单的操作
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 添加新用户按钮事件
    submitUser () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
        }
        // 发送请求
        this.addForm.mobile = this.addForm.phone
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
          return
        }
        this.$message.success('添加成功')
        // 隐藏对话框
        this.dialogFormVisible = false
        // 重新获取用户列表
        this.getUserList()
      })
    },
    async showEditUser (id) {
      // 根据id去查询用户的信息
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        this.$message.error('该用户信息不存在')
        return
      }
      res.data.phone = res.data.mobile
      this.editForm = res.data
      //   this.editForm.phone = res.data.mobile
      console.log(this.editForm)

      this.editDialogFormVisible = true
    },
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    submitEditUser () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        // 发送请求
        this.addForm.mobile = this.addForm.phone
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.phone
          }
        )
        if (res.meta.status !== 200) {
          this.$message.error('修改用户失败')
          return
        }
        this.$message.success('修改成功')
        // 隐藏对话框
        this.editDialogFormVisible = false
        // 重新获取用户列表
        this.getUserList()
      })
    },
    // 删除用户的按钮
    async deleteEditUser (id) {
      const isConfirm = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      console.log(isConfirm)
      if (isConfirm !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        this.$message.error('删除失败！')
        return
      }
      this.$message.success('删除成功')
      this.getUserList()
    },
    async setRole (id) {
      this.users.some(item => {
        if (item.id === id) {
          this.tempUser = item
        }
      })
      // 发送请求获取所有的角色
      const { data: res } = await this.$http.get('roles')
      this.roleList = res.data
      res.data.forEach(item => {
        if (item.roleName === this.tempUser.role_name) {
          this.tempUser.roleId = item.id
        }
      })
      this.selectRoleId = this.tempUser.roleId
      this.setRoleDialogVisible = true
    },
    // 关闭分配角色弹出框
    closeSetRole () {},
    // 分配角色提示框点击确定按钮后的提交动作
    async submitSetRole (userId, roleId) {
      const { data: res } = await this.$http.put(`users/${userId}/role`, {
        rid: roleId
      })
      console.log(123)
      console.log(res)

      if (res.meta.status !== 200) {
        this.$message.error('分配角色失败')
      }
      this.$message.success('分配角色成功')
      this.setRoleDialogVisible = false
      this.getUserList()
    },
    selectRole (val) {
      console.log(val)
      this.selectRoleId = val
      console.log(this.tempUser)
    }
  }
}
</script>

<style>
</style>
